package com.mls.fivedistrict.controller.common;

import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.controller.portal.UserController;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.server.CommonService;
import com.mls.fivedistrict.server.PropertyService;
import com.mls.fivedistrict.server.SysSettingService;
import com.mls.fivedistrict.server.UserService;
import com.mls.fivedistrict.util.OSSTools;
import com.mls.fivedistrict.util.jedis.RedisPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by chenxiuxiang on 2018/3/16.
 */
@RestController
@RequestMapping("/api/common")
public class CommonController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Resource(name = "commonService")
    CommonService commonService;
    @Resource(name = "sysSettingService")
    SysSettingService sysSettingService;

    @Resource(name = "propertyService")
    PropertyService propertyService;

    @Resource(name = "userService")
    UserService userService;

    @PostMapping(path = "/v1/captcha")
    public ServiceResponse getCaptcha(@RequestBody Map<String, String> params) {
        String phone = Optional.ofNullable(params.get("phone")).orElseThrow(() -> new CustomerException("手机号不存在"));
        String type = Optional.ofNullable(params.get("type")).orElseThrow(() -> new CustomerException("验证码类型不存在"));

        return commonService.getCaptcha(phone, type);
    }


    @PostMapping(path = "/v1/upload")
    public ServiceResponse upload(@RequestParam("uploadFile") MultipartFile file, HttpServletRequest request, Map<String, String> params) throws IOException {
        Optional.ofNullable(file).orElseThrow(() -> new CustomerException("文件不存在"));
        String fileName = file.getOriginalFilename();
        String leftPath = request.getServletContext().getRealPath("/images");
        File newFile = new File(leftPath, fileName);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        file.transferTo(newFile);
        OSSTools tools = new OSSTools();
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        String fileType = "image/" + type;
        fileName = UUID.randomUUID().toString() + "." + type;
        String logoPath = tools.uploadObj("image", fileName, newFile, fileType);
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        LOGGER.info(logoPath);
        return ServiceResponse.createSuccessResponse(logoPath);
    }

    @PostMapping(path = "/v1/uploadFile")
    public ServiceResponse uploadFile(@RequestParam("uploadFile") MultipartFile file, HttpServletRequest request, Map<String, String> params) throws IOException {
        Optional.ofNullable(file).orElseThrow(() -> new CustomerException("文件不存在"));
        String fileName = file.getOriginalFilename();
        String leftPath = request.getServletContext().getRealPath("/images");
        File newFile = new File(leftPath, fileName);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        file.transferTo(newFile);
        OSSTools tools = new OSSTools();
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        String fileType = "image/" + type;
        fileName = UUID.randomUUID().toString() + "." + type;
        String logoPath = tools.uploadObj("systemUpload", fileName, newFile, fileType);
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        LOGGER.info(logoPath);
        return ServiceResponse.createSuccessResponse(logoPath);
    }


    @RequestMapping(path = "/v1/uploadForTinymce")
    public Map<String, Object> upload1(@RequestParam("file") MultipartFile file, HttpServletRequest request, Map<String, String> params) throws IOException {
        Optional.ofNullable(file).orElseThrow(() -> new CustomerException("文件不存在"));
        String fileName = file.getOriginalFilename();
        String leftPath = request.getServletContext().getRealPath("/images");
//        if (1 == 1) {
//            Map<String, Object> datas = new HashMap<>();
//            Map<String, String> files = new HashMap<>();
//            files.put("file", "http://dwqvip.oss-cn-shenzhen.aliyuncs.com/image/ab33d4c5-ccb0-4ff3-9857-2931b9be1e24.jpg");
//            datas.put("files", files);
//            return datas;
//        }
        File newFile = new File(leftPath, fileName);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        file.transferTo(newFile);
        OSSTools tools = new OSSTools();
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        String fileType = "image/" + type;
        fileName = UUID.randomUUID().toString() + "." + type;
        String logoPath = tools.uploadObj("systemUpload", fileName, newFile, fileType);
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        Map<String, Object> datas = new HashMap<>();
        Map<String, String> files = new HashMap<>();
        files.put("file", logoPath);
        datas.put("files",files);
        LOGGER.info(logoPath);
        return datas;
    }


    @GetMapping("/v1/setting")
    public ServiceResponse getSysSetting() {
        return sysSettingService.getSysSettings();
    }

    @PostMapping(path = "/v1/verify/captcha")
    public ServiceResponse verifyCaptcha(@RequestBody Map<String, String> params) {
        String phone = Optional.ofNullable(params.get("phone")).orElseThrow(() -> new CustomerException("手机号不存在"));
        String code = Optional.ofNullable(params.get("code")).orElseThrow(() -> new CustomerException("验证码不存在"));
        String catchCode = RedisPoolUtil.get(phone);
        if (!code.equals(catchCode)) {
            return ServiceResponse.createErrorResponse("验证码错误");
        }

        return ServiceResponse.createSuccessResponse();
    }

    @GetMapping("/v1/enums")
    public ServiceResponse getEnumList() {
        return ServiceResponse.createSuccessResponse(commonService.getEnums());
    }

    @GetMapping("/v1/enum/{enumName}")
    public ServiceResponse getEnumDetail(@PathVariable String enumName) {
        return ServiceResponse.createSuccessResponse(commonService.getEnumDetail(enumName));
    }


}
